<script setup lang="ts">
import { ref, Ref, isRef, shallowRef, triggerRef, customRef } from "vue";

const message = "hello Ref 全家桶";
const number = ref("");
type Cls = {
  blue: boolean;
  border: boolean;
};
const flag: Cls = {
  blue: true,
  border: true,
};
let info = "hello Info";
const handleInfo = () => {
  info = "info info";
};
// Ref TS对应的接口
// interface Ref<T> {
//   value: T
// }
let name: Ref<string> = ref("我是name");

const handleName = () => {
  name.value = "new Name value";
};
// isRef 用来判断是否是ref对象
// import { isRef } from "vue";
let reftrue: Ref<number> = ref(111);
let reffalse: number = 1111;

const isRefTrue = isRef(reftrue);
const isRefFalse = isRef(reffalse);

// shallowRef 创建一个跟踪自身value变化的ref,但不会使其值变为响应式的
// import { shallowRef } from "vue";
type objType = { name: string };
let obj: Ref<objType> = shallowRef({
  name: "hello",
});
const handleObj = () => {
  console.log("handleObjhandleObj");
  obj.value.name = "world";
};

// triggerRef  强制更新页面dom
// import { triggerRef } from "vue";
const handleObjTri = () => {
  obj.value.name = "handleObjTri";
  triggerRef(obj);
};

// customRef  是个工厂函数要求我们返回一个对象 并且实现 get 和 set
// import { customRef } from "vue";

function Myref<T>(value: T) {
  return customRef((track, trigger) => {
    return {
      get() {
        track();
        return value;
      },
      set(newVal: T) {
        console.log("set");
        value = newVal;
        trigger();
      },
    };
  });
}

let ObjCustom = Myref("ObjCustom");
const handleObjCustomRef = () => {
  ObjCustom.value = "handleObjCustomRef";
  // triggerRef(message)
};
</script>

<template class="ref-wrap">
  <div>
    <HelloWorld msg="Hello Vue 3 + TypeScript + Vite" />
    <div>{{ message }}</div>
    <div>{{ number }}</div>
    <input type="number" name="" id="" v-model="number" />
    <div :class="flag">{{ flag }}</div>
    <button @click="handleInfo">点我修改info</button>
    <div>{{ info }}</div>
    <button @click="handleName">点我修改Name</button>
    <div>{{ name }}</div>
    <div>isRef:{{ isRefTrue }}/////{{ isRefFalse }}</div>
    <div>obj:{{ obj }}</div>
    <button @click="handleObj">点我修改obj</button>
    <button @click="handleObjTri">点我强制修改obj</button>
    <div>{{ ObjCustom }}</div>
    <button @click="handleObjCustomRef">点我强制修改obj</button>
  </div>
</template>

<style scoped>
.ref-wrap {
  border: 1px solid pink;
}
</style>>
